package com.wuwei.tms.utils.token;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Date;

/**
 * 把员工工号转变成token
 */
@Component
public class TokenUtil {
    private static final String SECRET_KEY = "7B4AE8CC3FAA8E7B10B96E90AE076C6F0302657C4081ED5502EF2AF6224AF42F";
    private static final long EXPIRATION_TIME = 2592000000L; // 30 days in milliseconds，有效期30天

    public static String generateToken(Long empno) {
        Date now = new Date();
        Date expirationDate = new Date(now.getTime() + EXPIRATION_TIME);

        return Jwts.builder()
                .setSubject(String.valueOf(empno))
                .setIssuedAt(now)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    public static Long getEmpnoFromToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();

        String subject = claims.getSubject();
        return Long.valueOf(subject);
    }
}
